package cn.itcast.service.impl;

import cn.itcast.pojo.Weather;
import cn.itcast.service.WeatherService;
import cn.itcast.utils.CityCodeUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
public class WeatherServiceImpl implements WeatherService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     *
     * @param cityName 城市名称
     * @return 5天的城市天气信息
     */
    @Override
    public List<Weather> getCityWeatherInfo(String cityName) {
        //1.根据城市名称获取城市编号
        String cityCode = CityCodeUtils.getCityCode(cityName);
        //2.通过restTemplate发送http请求获取城市添加
        String url = "http://t.weather.itboy.net/api/weather/city/" + cityCode;
        String respBody = restTemplate.getForObject(url, String.class);
        //3.使用FastJSON对结果进行解析
        //3.1将响应的json字符串转化为jsonObject
        JSONObject jsonObject = JSON.parseObject(respBody);
        int status = jsonObject.getIntValue("status");
        if(status == 200) {
            //3.2响应成功,获取data数据
            JSONObject data = jsonObject.getJSONObject("data");
            //3.3 获取forecast
            JSONArray jsonArray = data.getJSONArray("forecast");
            List<Weather> list = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                JSONObject info = jsonArray.getJSONObject(i);
                String date = info.getString("date");
                String high = info.getString("high");
                String low = info.getString("low");
                String ymd = info.getString("ymd");
                String week = info.getString("week");
                String fx = info.getString("fx");
                String fl = info.getString("fl");
                String type = info.getString("type");
                String notice = info.getString("notice");
                Weather weather = new Weather(type,high,low,ymd,week,fx,fl,notice);
                list.add(weather);
            }
            return list;
        }
        return Collections.emptyList();
    }
}
